package com.crazyhat.crazyhat.utils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;

import com.aliyun.imageaudit20191230.Client;
import com.aliyun.imageaudit20191230.models.ScanImageAdvanceRequest;
import com.aliyun.imageaudit20191230.models.ScanImageAdvanceRequest.ScanImageAdvanceRequestTask;
import com.aliyun.imageaudit20191230.models.ScanImageResponse;
import com.aliyun.imageaudit20191230.models.ScanImageResponseBody.ScanImageResponseBodyDataResults;
import com.aliyun.imageaudit20191230.models.ScanImageResponseBody.ScanImageResponseBodyDataResultsSubResults;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

public class ScanImage {

    private static final String accessKeyId;

    private static final String accessKeySecret;

    private static final String endpoint;

    private static final List<String> sceneList;


    static{
        accessKeyId = "LTAI5tNLKg5bJqoWTfE7F8TV";
        accessKeySecret = "CamuvHp799UttRdombWsfsGMD3qAxx";

        
        endpoint="imageaudit.cn-shanghai.aliyuncs.com";


        /*  设置检测类型列表
         * porn：图片智能鉴黄
         * terrorism：图片敏感内容识别、图片风险人物识别
         * ad：图片垃圾广告识别
         * live：图片不良场景识别
         * logo：图片Logo识别
         */
        sceneList = new ArrayList<String>();
        sceneList.add("porn");
        sceneList.add("ad");
    }

    private static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {

        Config config = new Config()
            .setAccessKeyId(accessKeyId)
            .setAccessKeySecret(accessKeySecret)
            .setEndpoint(endpoint);


        return new Client(config);
    }

    /**
     * 对图片列表进行审核
     * @param fileList
     * @return
     */
    public static List<ScanImageResponseBodyDataResults> scanImageList(List<MultipartFile> fileList) {

        if (fileList==null) {
            return null;
        }

        Client client;
        try {
            client = createClient(accessKeyId, accessKeySecret);
        } catch (Exception e) {

            e.printStackTrace();

            return null;
        }

        //本地InputStream
        List<ScanImageAdvanceRequestTask> taskLocalList = new ArrayList<>();

        for(MultipartFile item:fileList) {

            if (item==null) {
                continue;
            }

            try{
                //本地InputStream
                ScanImageAdvanceRequestTask  taskLocal= new ScanImageAdvanceRequestTask();
                taskLocal.setDataId(item.getOriginalFilename());
                taskLocal.setImageTimeMillisecond(1L);
                taskLocal.setInterval(1);
                taskLocal.setMaxFrames(1);
                taskLocal.setImageURLObject(item.getInputStream());

                taskLocalList.add(taskLocal);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        ScanImageAdvanceRequest scanImageAdvanceRequest = new ScanImageAdvanceRequest()
                .setTask(taskLocalList)
                .setScene(sceneList);

        RuntimeOptions runtime = new RuntimeOptions();

        try {

            ScanImageResponse scanImageResponse = client.scanImageAdvance(scanImageAdvanceRequest, runtime);

            List<ScanImageResponseBodyDataResults> resultList=scanImageResponse.getBody().getData().getResults();

            /*
             * 建议您执行的操作。
             * pass：图片正常，无需进行其余操作；或者未识别出目标对象。
             * review：检测结果不确定，需要进行人工审核；或者未识别出目标对象。
             * block：图片违规，建议执行进一步操作（如直接删除或做限制处理）。
             */

            return resultList;

        } catch (com.aliyun.tea.TeaException teaException) {

            System.out.println("图片检测出现异常");

        } catch(Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    
    /**
     * 定时扫描
     * @param fileList
     */
    public static void scheduledScan(List<String> fileList){
        if (fileList==null) {
            return;
        }

        Client client;
        try {
            client = createClient(accessKeyId, accessKeySecret);
        } catch (Exception e) {

            e.printStackTrace();

            return;
        }

        //本地InputStream
        List<ScanImageAdvanceRequestTask> taskLocalList = new ArrayList<>();

        for(String item:fileList) {

            if (item==null) {
                continue;
            }
            
            try{
                //本地InputStream
                URI uri=new URI(item);
                
                ScanImageAdvanceRequestTask  taskLocal= new ScanImageAdvanceRequestTask();
                taskLocal.setDataId(item);
                taskLocal.setImageTimeMillisecond(1L);
                taskLocal.setInterval(1);
                taskLocal.setMaxFrames(1);
                taskLocal.setImageURLObject(uri.toURL().openStream());

                taskLocalList.add(taskLocal);

            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        ScanImageAdvanceRequest scanImageAdvanceRequest = new ScanImageAdvanceRequest()
                .setTask(taskLocalList)
                .setScene(sceneList);

        RuntimeOptions runtime = new RuntimeOptions();

        try {

            ScanImageResponse scanImageResponse = client.scanImageAdvance(scanImageAdvanceRequest, runtime);

            List<ScanImageResponseBodyDataResults> resultList=scanImageResponse.getBody().getData().getResults();

            /*
             * 建议您执行的操作。
             * pass：图片正常，无需进行其余操作；或者未识别出目标对象。
             * review：检测结果不确定，需要进行人工审核；或者未识别出目标对象。
             * block：图片违规，建议执行进一步操作（如直接删除或做限制处理）。
             */

            if (resultList!=null) {
                resultList.forEach((item)->{
                    if (item!=null) {
                        if (!(isApproved(item, true))) {
                            ObsUtil.deleteFile(item.getDataId());
                        }
                    }
                });
            }

        } catch (com.aliyun.tea.TeaException teaException) {

        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 对单张图片进行审核并返回是否违规结果
     * @return 不违规：true，违规：false
     */
    public static boolean scanAndApprove(MultipartFile file,Boolean strict) {

        List<ScanImageResponseBodyDataResults> resultList = scanImageList(List.of(file));

        if (resultList==null) {
            return false;
        }

        if (strict==null) {
            strict=true;
        }

        return isApproved(resultList.get(0),strict);
    }

    /**
     * 图片是否审核通过
     */
    public static boolean isApproved(ScanImageResponseBodyDataResults result,boolean strict) {

        if (result==null) {
            return false;
        }

        List<ScanImageResponseBodyDataResultsSubResults> subResultsList = result.getSubResults();

        if (subResultsList==null) {
            return false;
        }

        if (strict) {

            //严格审核，只有都为pass，才通过
            for(ScanImageResponseBodyDataResultsSubResults subResult:subResultsList) {
                if (!("pass".equals(subResult.getSuggestion()))) {
                    return false;
                }
            }
        } else {

            //非严格审核，只有都不为block才通过
            for(ScanImageResponseBodyDataResultsSubResults subResult:subResultsList) {
                if ("block".equals(subResult.getSuggestion())) {
                    return false;
                }
            }
        }

        return true;
    }
}
